

import 'dart:convert';

import 'package:thingskit/apiService/ApiService.dart';
import 'package:thingskit/utils/const.dart';

class UserInfo {
  final String accountExpireTime; // 账号过期时间
  final String avatar; // 头像
  final String createTime; // 创建时间
  final String email;// 邮箱
  final String homePath;// 首页路径
  final bool needSetPwd;// 是否需要设置密码
  final String phone;// 手机号
  final List<Role> plainRoles;//  角色
  final String name;// 真实姓名
  final List<String> roles;// 角色
  final String tenantId; // 租户id
  final String tenantName;// 租户名称
  final String userId;// 用户id
  final String username;// 用户名

  UserInfo({
    this.accountExpireTime='',
    this.avatar='',
    this.createTime='',
    this.email='',
    this.homePath='',
    this.needSetPwd=false,
    this.phone='',
    this.plainRoles=const [],
    this.name='',
    this.roles=const [],
    this.tenantId='',
    this.tenantName='',
    this.userId='',
    this.username='',
  }
  );

  factory UserInfo.fromJson(Map<String, dynamic> json) {
    return UserInfo(
      accountExpireTime: json['accountExpireTime'] ?? '',
      avatar: json['avatar'] ?? '',
      createTime: json['createTime'] ?? '',
      email: json['email'] ?? '',
      homePath: json['homePath'] ?? '',
      needSetPwd: json['needSetPwd'] ?? false,
      phone: json['phone'] ?? '',
      plainRoles: (json['plainRoles'] as List<dynamic>?)
          ?.map((e) => Role.fromJson(e))
          .toList() ??
          [],
      name: json['name'] ?? 'admin',
      roles: List<String>.from(json['roles'] ?? []),
      tenantId: json['tenantId'] ?? '',
      tenantName: json['tenantName'] ?? '',
      userId: json['userId'] ?? '',
      username: json['username'] ?? '',
    );
  }


  Map<String, dynamic> toJson() {
    return {
      'accountExpireTime': accountExpireTime,
      'avatar': avatar,
      'createTime': createTime,
      'email': email,
      'homePath': homePath,
      'needSetPwd': needSetPwd,
      'phone': phone,
      'plainRoles': plainRoles.map((e) => e.toJson()).toList(),
      'name': name,
      'roles': roles,
      'tenantId': tenantId,
      'tenantName': tenantName,
      'userId': userId,
      'username': username,
    };
  }

}
class Role {
  final String roleId;
  final String roleName;

  Role({
    this.roleId='',
    this.roleName='',
  });

  factory Role.fromJson(Map<String, dynamic> json) {
    return Role(
      roleId: json['roleId'] ?? '',
      roleName: json['roleName'] ?? '',
    );
  }

  Map<String, dynamic> toJson() {
    return {
      'roleId': roleId,
      'roleName': roleName,
   };
  }
}

class UserApi extends ApiService{
  UserApi() : super(thingskitUrl);

  Future<UserInfo?> getUserInfo() async {
    final response = await getRequest('/user');
    if (response == null) {
      return null;
    }
    return UserInfo.fromJson(response);
  }
}